package com.weixin.mp.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 阿里云OSS工具类
 */
@Slf4j
@Component
public class OssUtils {

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.avatarDir}")
    private String avatarDir;

    @Value("${oss.domain}")
    private String domain;

    /**
     * 上传头像到OSS
     * @param file 文件对象
     * @return 返回访问URL
     */
    public String uploadAvatar(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String extension = getFileExtension(originalFilename);
        String fileName = UUID.randomUUID().toString() + extension;
        String objectName = avatarDir + fileName;

        OSS ossClient = null;
        try {
            // 创建OSSClient实例
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            
            // 上传文件
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(file.getBytes()));
            
            // 返回文件访问路径
            return domain + "/" + objectName;
        } catch (IOException e) {
            log.error("上传头像到OSS失败", e);
            throw new RuntimeException("上传头像失败: " + e.getMessage());
        } finally {
            // 关闭OSSClient
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 获取文件扩展名
     * @param fileName 文件名
     * @return 扩展名（包含.）
     */
    private String getFileExtension(String fileName) {
        if (fileName == null || fileName.lastIndexOf(".") == -1) {
            return ".jpg"; // 默认使用jpg格式
        }
        return fileName.substring(fileName.lastIndexOf("."));
    }
} 